/*
* 封装 CRUD 操作
* 读取MySQL中地磅数据（上报到云端的地磅数据）
*/

const db = require('../lib/mysql/db.js');

// 创建
exports.createAvs = async (avsData) => {
    const sql = 'INSERT INTO weighbridge_yongqiang2 (weighid, truckno, firstdatetime, seconddatetime, net) VALUES (?, ?, ?, ?, ?)';
    const {
        id,
        truckno,
        firstdatetime,
        seconddatetime,
        net
    } = avsData;
    const result = await db.query(sql, [id, truckno, firstdatetime, seconddatetime, net]);
    return result.insertId;
};

// 通过ID获取
exports.getAvsById = async (id) => {
    const sql = 'SELECT * FROM weighbridge_yongqiang2 WHERE id = ?';
    const rows = await db.query(sql, [id]);
    return rows[0];
};

// 获取今日垃圾类型分类统计数据
exports.getAvsGroupByRange = async (start_time, end_time) => {
    const sql = 'SELECT product, SUM(net) as value, count(id) as num FROM weighbridge_yongqiang2 where seconddatetime >= ? and seconddatetime <= ? group by product';
    const rows = await db.query(sql, [start_time, end_time]);
    return rows;
};

// 更新
exports.updateAvs = async (id, avsData) => {
    const sql = 'UPDATE weighbridge_yongqiang2 SET truckno = ?, firstdatetime = ?, seconddatetime = ?, net = ? WHERE id = ?';
    const {
        truckno,
        firstdatetime,
        seconddatetime,
        net
    } = avsData;
    await db.query(sql, [truckno, firstdatetime, seconddatetime, net, id]);
};

// 删除
exports.deleteAvs = async (id) => {
    const sql = 'DELETE FROM weighbridge_yongqiang2 WHERE id = ?';
    await db.query(sql, [id]);
};
